package com.coms514.scheduleme;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class CaregiverActivity extends Activity {

	static final String TAG = "CaregiverActivity";

	private static final int CONTEXT_EDIT = 0;
	private static final int CONTEXT_DELETE = 1;
	private final static int ADD_OR_EDIT_CAREGIVER_REQUEST = 2;

	private ArrayList<String> id = new ArrayList<String>();
	private ArrayList<String> name = new ArrayList<String>();
	private ArrayList<String> email = new ArrayList<String>();
	private ArrayList<String> phone = new ArrayList<String>();
	
	private ListView listView;
	CaregiverAdapter adapter;
	
	ScheduleMeDatabase database;
	private boolean dbIsOpen;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		println(">>> Entering CaregiverActivity.onCreate()");
		
		// view and menu
		setContentView(R.layout.caregiverlist);
		listView = (ListView) findViewById(R.id.list);
		registerForContextMenu(listView);
		
		// open database
		if (database != null) {
			database.close();
			database = null;
		}
		
		database = ScheduleMeDatabase.getInstance(this);
		dbIsOpen = database.open();
	}
		
	@Override
	protected void onResume() {
		displayData();
		super.onResume();
	}
	
	private void displayData() {
		if (!dbIsOpen) {
			dbIsOpen = database.open();
		}
		id.clear();
		name.clear();
		email.clear();
		phone.clear();
		
		Cursor cursor = getCaregiver();
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			id.add(cursor.getString(cursor.getColumnIndex("_id")));
			name.add(cursor.getString(cursor.getColumnIndex("name")));
			email.add(cursor.getString(cursor.getColumnIndex("email")));
			phone.add(cursor.getString(cursor.getColumnIndex("phone")));
		}
		
		adapter = new CaregiverAdapter(CaregiverActivity.this, id, name, email, phone);
		listView.setAdapter(adapter);

		cursor.close();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		switch (requestCode) {
			case ADD_OR_EDIT_CAREGIVER_REQUEST:
				if (resultCode == Activity.RESULT_OK) {
					// insert or update
					String id = data.getStringExtra("id");
					String name = data.getStringExtra("name");
					String email = data.getStringExtra("email");
					String phone = data.getStringExtra("phone");
					
					saveCaregiver(id, name, email, phone);
				}
				break;
		}
	}

    @Override
    public void onDestroy(){
        super.onDestroy();
        database.close();
    }
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(0, CONTEXT_EDIT, 0, R.string.edit_caregiver);
		menu.add(0, CONTEXT_DELETE, 0, R.string.delete_caregiver);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		int caregiverIndex = (int) info.position;
		println("caregiverIndex=" + caregiverIndex);
		
		if (caregiverIndex < adapter.getCount()) {
			final String id = adapter.getId(caregiverIndex);
			final String name = adapter.getName(caregiverIndex);
			final String email = adapter.getEmail(caregiverIndex);
			final String phone = adapter.getPhone(caregiverIndex);
			
			switch (item.getItemId()) {
				case CONTEXT_EDIT:
					startAddOrEditCaregiverActivity(id, name, email, phone);
					return true;
					
				case CONTEXT_DELETE:
					new AlertDialog.Builder(this).setTitle(R.string.caregiver_delete_title)
						.setMessage(name)
						.setCancelable(false)
						.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog, int which) {
								// delete the caregiver with id
								deleteCaregiver(id);
								displayData();								
							}
						})
						.setNegativeButton(R.string.no, null)
						.create()
						.show();
					
					return true;
			}
		}
		return super.onContextItemSelected(item);
	}

	public void onAddClick(View view) {
		startAddOrEditCaregiverActivity(null, null, null, null);
	}

  	private void startAddOrEditCaregiverActivity(String id, String name, String email, String phone) {
  		Intent intent = new Intent(this, AddOrEditCaregiverActivity.class);
  		if (id != null) {
  			intent.putExtra("id", id);
  			intent.putExtra("name", name);
  			intent.putExtra("email", email);
  			intent.putExtra("phone", phone);
  		}
  		startActivityForResult(intent, ADD_OR_EDIT_CAREGIVER_REQUEST);
  	}
  	
  	private Cursor getCaregiver() {
  		String selectCaregiver = "select _id, name, email, phone from caregiver";
  		Cursor cursor = database.rawQuery(selectCaregiver);
  		return cursor;
  	}
  	
  	private void saveCaregiver(String id, String name, String email, String phone) {
  		if (id != null) {			// update
  			database.execSQL("update caregiver set name = '" + name + "', email = '" + email + "', phone = '" + phone + "'"
  					+ " where _id = " + id);
  		} else {					// insert
  			database.execSQL("insert into caregiver (name, email, phone) "
  					+ " values ('" + name + "', '" + email + "', '" + phone + "')");
  		}  			
  	}
  	
  	private void deleteCaregiver(String id) {
		database.execSQL("delete from caregiver where _id = " + id);
  	}

	/* for logging */
	private void println(String msg) {
		Log.d(TAG, msg);
	}
}

